package com.tencent.examples.blueking.mysql.service;

import com.alibaba.fastjson.JSONObject;
import com.tencent.bk.utils.blueking.properties.ApiUrlProperties;
import com.tencent.bk.utils.blueking.tools.HttpsClient;
import com.tencent.examples.blueking.extend.QueryParam;
import com.tencent.examples.blueking.mongo.service.ObjectBaseService;
import com.tencent.examples.blueking.mysql.extend.biz.CrudBiz;
import com.tencent.examples.blueking.mysql.model.BkSaveNavigationBar;
import com.tencent.examples.blueking.mysql.repository.BkSaveNavigationBarRepository;
import com.tencent.examples.core.processor.BlueKingProcessor;
import com.tencent.examples.core.processor.common.CommParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class BkSaveNavigationBarService extends CrudBiz<BkSaveNavigationBarRepository, BkSaveNavigationBar> {

    /**
     * EntityManager持久层对象
     */
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    JobStoreTimeService jobStoreTimeService;
    @Autowired
    ObjectBaseService objectBaseService;
    @Autowired
    BlueKingProcessor blueKingProcessor;
    @Autowired
    CommParams commParams;
    @Autowired
    ApiUrlProperties apiUrlProperties;

    @Override
    public Specification<BkSaveNavigationBar> getSearchCondition(Map<String, String> queryHash) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>(); //所有的断言
            predicates.add(criteriaBuilder.equal(root.get("deleteStatus").as(Boolean.class), false));
            String bk_userName = queryHash.get("bk_userName");
            if (StringUtils.isNotEmpty(bk_userName)) {
                predicates.add(criteriaBuilder.equal(root.get("bk_userName").as(String.class), bk_userName));
            }
            String bk_obj_id = queryHash.get("bk_obj_id");
            if (StringUtils.isNotEmpty(bk_obj_id)) {
                predicates.add(criteriaBuilder.equal(root.get("bk_obj_id").as(String.class), bk_obj_id));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
    }

    @Override
    @Transactional(readOnly = true)
    public List<BkSaveNavigationBar> findList(QueryParam queryParam) {
        return dao.findAll(getSearchCondition(queryParam.getSqlMap()));
    }

    @Override
    @Transactional(readOnly = true)
    public Page<BkSaveNavigationBar> findList(Pageable pageable, QueryParam queryParam) {
        return dao.findAll(getSearchCondition(queryParam.getSqlMap()), pageable);
    }

    @Override
    @Transactional(readOnly = true)
    public BkSaveNavigationBar findModel(Long id) {
        return dao.findOne(id);
    }

    @Override
    @Transactional(readOnly = false)
    public void add(BkSaveNavigationBar model) {
//        model.setCreateDate(new Date());
        dao.save(model);
    }

    @Override
    @Transactional(readOnly = false)
    public void update(BkSaveNavigationBar model) {
        BkSaveNavigationBar existModel = dao.findOne(model.getId());
        BeanUtils.copyProperties(model, existModel);
//        existModel.setUpdateDate(new Date());
    }

    @Override
    @Transactional(readOnly = false)
    public void addOrUpdate(BkSaveNavigationBar model) {
        if (model.getId() != null && model.getId() > 0) {
            update(model);
        } else {
            add(model);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(Long id) {
        dao.delete(id);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete_logic(BkSaveNavigationBar model) {
        BkSaveNavigationBar bkStoreTime = dao.findOne(model.getId());
//        bkStoreTime.setDeleteStatus(true);
    }

    /**
     * 查询每天的门店的开店闭店时间
     *
     * @param week 星期几
     * @return
     */
    public List getStoreTimeDayJob(Integer week) {
        String sql = "SELECT business_open_time,business_close_time,GROUP_CONCAT(DISTINCT inst_id) FROM bk_store_time \n" +
                "WHERE delete_status=FALSE \n" +
                "AND business_close_time!='' AND business_close_time IS NOT NULL\n" +
                "AND business_open_time!='' AND business_open_time IS NOT NULL\n" +
                "AND global_id IS NOT NULL AND inst_id IS NOT NULL\n" +
                "AND day_of_week_mon1sun7=" + week + "\n" +
                "GROUP BY business_open_time,business_close_time\n";
        return entityManager.createNativeQuery(sql).getResultList();
    }

    public String getUserName(HttpServletRequest request) {
        String bk_username = "";
        JSONObject jsonObject = commParams.initJsonOtherMethod(request);
        JSONObject resultObject = HttpsClient.httpRequest(apiUrlProperties.getGet_user(), "POST", jsonObject.toString());
        if (resultObject.getBoolean("result")) {
            JSONObject dataObject = resultObject.getJSONObject("data");
            bk_username = dataObject.getString("bk_username");
        }

        return bk_username;
    }
}
